import requests
from datetime import datetime, timedelta

from air_web.config.config import config
from air_web.data_platform import sql_engine


def get_delay_min():
    sql = f"select value from sys_config where name='delay'"
    delay_df = sql_engine.query(sql)
    delay_min = int(delay_df["value"].tolist()[0])
    return delay_min


def get_end_time(start_time):
    if start_time is None:
        return None
    start_time = (
        datetime.strptime(start_time, "%Y-%m-%d")
        if isinstance(start_time, str)
        else start_time
    )
    if start_time.date() == datetime.now().date():
        end_time = datetime.now()
    else:
        end_time = start_time + timedelta(days=1)
    return end_time


class AirBase:
    BASE_URL = "http://25.214.217.116:20081/"

    def __init__(self, log, today_str=None, baseline_str=None):
        self.log = log
        self.sql_engine = sql_engine

        self.today_str = (
            today_str
            if today_str
            else datetime.now().date().strftime("%Y-%m-%d")
        )
        self.today_end = get_end_time(self.today_str)

        # self.baseline_str = (
        #     baseline_str if baseline_str else get_baseline_day(self.today_str)
        # )
        # self.baseline_end = get_end_time(self.baseline_str)

    def post_data(self, data_url, data):
        url = self.BASE_URL + data_url
        for i in range(3):
            self.log.info(f"start reqeust {url}")
            if not data or len(data) == 0:
                self.log.warning(f" data is null : {data}")
                return
            resp = requests.post(url=url, json=data)
            self.log.info(resp.content)
            if resp.status_code == 200:
                return
